package sg.edu.nus.comp.icreate.ivletalk.utils.net;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.os.AsyncTask;
import android.util.Log;

public class DataPoster extends AsyncTask<Void, Void, String> {
	private HttpClient httpclient = new DefaultHttpClient();
	private HttpPost httpPost;
	private List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

	public DataPoster(String url) {
		httpPost = new HttpPost(url);
	}

	@Override
	protected String doInBackground(Void... params) {
		try {
			httpPost.addHeader("charset", HTTP.UTF_8);
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
			HttpResponse response = httpclient.execute(httpPost);
			long length = response.getEntity().getContentLength();
			InputStream contentStream = response.getEntity().getContent();
			byte[] b = new byte[(int) length];
			contentStream.read(b, 0, (int) length);
			String result = new String(b, 0, (int) length);
			return result;
		} catch (Exception e) {
			Log.e("err", "error new post", e);
			return null;
		}
	}

	public HttpPost getHttpPost() {
		return httpPost;
	}

	public List<NameValuePair> getNameValuePairs() {
		return nameValuePairs;
	}

	public void addNameValuePair(String name, String value) {
		nameValuePairs.add(new BasicNameValuePair(name, value));
	}
}
